<template>
  <div class="order-buy">
		<div class="order-con">
			<!-- 配送方式 -->
      <mode-distribution
        ref="modeDistribution"
        v-if="resData.list_shipping"
        :listShipping="resData.list_shipping"
				:shippingType='formData.shipping_type'
        :buyLists="resData.buy_lists"
        @getShippingType="getShippingType"
        @getSelfAddress="getSelfAddress"
        @getDateTime="getDateTime"
        :store_delivery="resData.store_delivery"
        ></mode-distribution>

      <!-- 地址管理 -->
      <address-admin  ref="addressAdmin"
                      :shippingType='formData.shipping_type'
                      :shippingTemp="resData.shipping_temp"
                      v-if="resData.address"
                      :addressArr="resData.address"
                      :takeTheirName="resData.take_their_name"
                      :storeHideMobile="resData.storeHideMobile || 1"
                      :tmpdata="selfAddressInfo"
                      @openSelfAddress="openSelfAddress"
                     >
      </address-admin>
		</div>
		 <!-- 商品信息 -->
    <goods-info :buyLists="resData.buy_lists"
                :point_name="resData.point_name"
                ></goods-info>
		<!--  -->
    <section class="item-block item-block2">
			<!-- 预约时间 -->
      <div class="item-box" v-if="resData.is_store_reservation_service==1 && isShowSubscribe" @click="selectSubDate">
          <span class="item-title">预约时间</span>
          <div class="item-con">
            <span class="item-span">{{subscribeTime?subscribeTime:'请选择时间'}}</span>
            <!-- <svg-icon icon-class="icon_right" class="class-icon"></svg-icon> -->
            <i class="icon-right"></i>
          </div>
      </div>
			<!-- 配送运费 -->
      <section class="item-box" v-if="resData.is_freight==0 && resData.scanCode !=1 && is_open_balance_pay">
        <span class="item-title">配送运费</span>
        <section class="item-con">
          <span class="item-span span-def" v-if="resData.freight_payer4 == 1">到付</span>
          <span v-if="resData.freight_payer4 !=1&&resData.full_mail_show" class="item-span span-def">({{resData.full_mail_show}})</span>
          <span v-if="resData.freight_payer4 !=1" class="item-span span-red"><i class="smallsize">&yen;</i>{{postFee}}{{formData.is_freight_collect==1?'（到付）':''}}</span>
        </section>
      </section>
			<!-- 买家留言 -->
      <section class="item-box">
        <span class="item-title">买家留言</span>
        <section class="item-con">
          <input class="item-input" name="message" v-model="formData.message" placeholder="选填，填写内容已和卖家协商确认"/>
        </section>
      </section>
      <section class="money-box">
        <!--总计-->
        <p class="msettlement_intle">
          <span>总兑换{{resData.point_name}}：</span>
          <span class="menoy-num">{{resData.total_points}}</span>
        </p>
      </section>
		</section>
		<!-- 余额支付 -->

		<div class="item-block item-block2">
      <div class="item-box" v-if="user_balance >0 && is_open_balance_pay && !tlfz_point_exchange">
        <van-checkbox class="item-title" :disabled="hfShowNoPay" v-model="money_type" checked-color="#F30C23" shape="square" icon-size="14px">
          使用余额
            <i>(余额：<span :class="hfShowNoPay ? 'hfSmall' : 'smallsize'">&yen;<b>{{user_balance}}</b></span>)</i>
          <template #icon="money_type">
            <img class="img-icon" :src="money_type.checked ? activeIcon : inactiveIcon" />
          </template>
        </van-checkbox>
      </div>
		</div>
    <!-- 其他支付方式 -->
    <div class="item-block item-block2" v-show="isShowOtherPayment">
      <pay-ment ref="payments"
          @globalAlipay="globalAlipay"
          :isTlfzPay="tlfz_point_exchange"
          :isHffzPay="true"
          v-model="paymentWay"></pay-ment>
       <div class="paymethodnote" v-if=" shop_info && shop_info.qipay_open && !resData.tuan_leader_needpay">
          <span>温馨提示：</span>支付宝支付{{shop_info.title}}已使用启博微付代收款业务，该笔订单将支付给启博科技，请放心支付！<br>
        </div>
    </div>
    <!-- 支付按钮 -->
    <section class="msettlement_sub">
      <div class="btn-addorder red-gra-btn" @click="openPayPop">提交订单</div>
    </section>
		<!-- 各种弹窗 -->
    <!-- 预约时间弹层 -->
    <subscribe ref="subscribe" @dateTime="dateTime"></subscribe>
    <!-- 正在支付中 -->
    <div class="paypopnote" v-show="isSubmit"><span>正在提交中……</span></div>
  </div>
</template>

<script>
import modeDistribution from '../../../order/buy/components/modeDistribution/index.vue'
import addressAdmin from '../../../order/buy/components/addressAdmin/index.vue'
import subscribe from '../../../order/buy/components/subscribe/index.vue'
import goodsInfo from './components/goodsInfo/index.vue'
import { pointBuy, pointAddOrder } from '@/api/user/member/memberApi'
import { getPostFee, getPointPostFee } from '@/api/order/order'
import payMent from '@/components/Payment'
import Store from '@/utils/store'
import { isWeixinCient } from '@/utils/validate'
import { openPage } from '@/utils/utils.js'
// import activeIcon from '@img/check_icon.png'
// import inactiveIcon from '@img/uncheck__icon.png'
import Vue from 'vue'
import { Checkbox, CheckboxGroup } from 'vant'
// import { Switch, Uploader, Icon } from 'vant'
// import UploadImg from '@/components/UploadImg'
import small from '@/smallapp/small'

Vue.use(Checkbox).use(CheckboxGroup)
// Vue.use(Switch).use(Uploader).use(Icon)

export default Vue.extend({
  components: {
    modeDistribution,
    addressAdmin,
    goodsInfo,
    subscribe,
    payMent
  },
  data() {
    return {
      activeIcon: 'https://img.wifenxiao.com/h5-wfx/images/check_icon.png',
      inactiveIcon: 'https://img.wifenxiao.com/h5-wfx/images/uncheck__icon.png',
      isSubmit: false,
      isShowSubscribe: false, // 是否显示预约时间，通过配送方式判断
      isShowOtherPayment: true,
      subscribeTime: '',
      payMentText: '',
      paymentWay: 'wxpay',
      address: [],
      buyLists: [],
      item_id: [],
      point_exchange_id: [],
      num: [],
      sku_id: [],
      resData: {},
      list_shipping: {},
      selfAddressInfo: {}, // 自提信息
      shop_info: {},
      // 用于计算
      user_balance: 0, // 余额
      postFee: 0.00, // 运费
      money_type: false,
      // 提交表单数据
      formData: {
        'global_alipay_currency': '',
        'shipping_type': '',
        'address_id': '',
        'province_id': '',
        'area_id': '',
        'city_id': '',
        'message': '',
        'self_address_id': '',
        'is_dhs_virtual': '',
        'type': ''
      },
      is_open_balance_pay: 1,
      tlfz_point_exchange: false, // 定制 通联分账
      hfShowNoPay: false,
      remark: -1,
    }
  },
  watch: {
    'money_type'(val) {
      if (val) {
        this.money_type2 = false
        this.formData.money_type = 2
      } else {
        this.formData.money_type = ''
      }
      this.pointBuyCompare()
    },
    'postFee'(val) {
      this.formData.post_price = val
      this.pointBuyCompare()
    },
    'formData.address_id'(val) {
      this.getPostFee()
    },
    'formData.shipping_type'(val) {
      this.getPostFee()
    }
  },
  created() {
    if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
      this.remark = 1
    }
    this.init()
  },
  mounted() {
    if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
      window.addEventListener('wxshow', () => {
        let options = wx.getEnterOptionsSync();
        // wx1e18d140f890f2c5，wx308088053f4ecc3a
        if (options.scene == '1038' && options.referrerInfo.appId == this.hfAppId && this.remark == 2) {
          // 代表从收银台小程序返回
          that.Jump('pointOrder')
          // this.isSubmit = false
        }
      }),
      window.addEventListener('wxHide', () => {
        this.remark = 2
      })
    }
  },
  methods: {
    init() {
      this.$loadingWrap.show()
      const data = Store.fetch('pointBuy')
      // const data = {
      //   point_exchange_id: 423,
      //   num: 1,
      //   sku: ''
      // }
      pointBuy(data).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          const resData = res.data
          this.resData = res.data
          this.list_shipping = resData.list_shipping
          this.buyLists = resData.buy_lists
          this.user_balance = parseFloat(resData.user_balance)
          this.shop_info = resData.shop_info
          this.postFee = parseFloat(resData.post_fee).toFixed(2) // 运费
          this.address = resData.address
          // 定制 通联分账
          this.tlfz_point_exchange = resData.tlfz_point_exchange == 1
          // 默认勾选余额支付
          if (this.user_balance > 0 && resData.is_open_balance_pay) {
            this.money_type = true
          }
          // 定制 通联分账暂不显示余额
          if (this.tlfz_point_exchange) {
            this.money_type = false
          }
          this.buyLists.forEach((item, index) => {
            this.item_id.push(item.item_id)
            this.point_exchange_id.push(item.point_exchange_id)
            this.num.push(item.num)
            this.sku_id.push(item.sku_id)
          })
          // form表单
          this.formData.code = resData.code
          this.formData.item_id = this.item_id
          this.formData.point_exchange_id = this.point_exchange_id
          this.formData.num = this.num
          this.formData.sku_id = this.sku_id
          this.formData.is_freight = resData.is_freight
          this.is_open_balance_pay = resData.is_open_balance_pay
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // 是否显示付款详情
    openPayPop() {
      if (this.paymentWay == 'wxpay') {
        if (isWeixinCient()) { // 微信环境
          this.formData.type = 2
        } else { // 非微信环境
          this.formData.type = 12
        }
        this.payMentText = '微信支付'
      } else if (this.paymentWay == 'alipay') {
        this.formData.type = 1
        this.payMentText = '支付宝支付'
      } else if (this.paymentWay == 'Hdfkpay') {
        this.formData.type = 3
        this.payMentText = '货到付款'
      } else if (this.paymentWay == 'ylpay') {
        this.formData.type = 8
        this.payMentText = '银联支付'
      } else if (this.paymentWay == 'kqpay') {
        this.formData.type = 9
        this.payMentText = '快钱支付'
      } else if (this.paymentWay == 'globalAlipay') { // 国际支付宝
        this.formData.type = 15
        this.formData.global_alipay_currency = this.global_alipay_currency
        this.payMentText = '国际支付宝支付'
      } else if (this.paymentWay == 'htwxpay') { // 定制 hante
        this.formData.type = 16
        this.formData.hantepay = 1
        this.payMentText = '微信支付'
      } else if (this.paymentWay == 'htAlipay') { // 定制 hante
        this.formData.type = 16
        this.formData.hantepay = 2
        this.payMentText = '支付宝支付'
      } else if (this.paymentWay == 'goallpay') { // GoAllPay
        this.formData.type = 20
        this.payMentText = 'GoAllPay'
      } else if (this.paymentWay == 'Alipay') {
        this.formData.type = 21
        this.payMentText = '支付宝'
      } else if (this.paymentWay == 'UnionPay') {
        this.formData.type = 22
        this.payMentText = '银联'
      } else if (this.paymentWay == 'WeChatPay') {
        this.formData.type = 23
        this.payMentText = '微信支付'
      } else if (this.paymentWay == 'tlfzWxpay') {
        this.formData.type = 26
        this.formData.tlfz_pay_type = 1
      } else if (this.paymentWay == 'HipoWxPay') {
        this.formData.type = 27
        this.payMentText = '微信支付'
      }else if (this.paymentWay == 'hffzWxpay') { // 汇付分账 微信
        this.formData.type = 34
        this.formData.adapay_pay_type = 2
      }
      this.isSubmit = true
      pointAddOrder(this.formData).then(res => {
        this.isSubmit = false
        if (res.status == 1) {

          // window.location.href = res.data.redirect_url
          // if (this.formData.type == 2 && res.data.jsApiParameters) {
          //   smallpay.wxOrderPay(res.data.jsApiParameters)
          // }
          // 小程序微信支付
          // type 27  HipoPay微信支付
          if(this.formData.type == 2 && res.data.jsApiParameters){
            const payData = JSON.parse(res.data.jsApiParameters)
            const url = res.data ? res.data.redirect_url:''
            wx.requestPayment({
              timeStamp: payData.timeStamp,
              nonceStr: payData.nonceStr, //
              package: payData.package, //
              signType: payData.signType, //微信签名方式
              paySign: payData.paySign, //微信签名
              success: (res) => {
                // console.log(res)
                openPage(url)
              },
              fail: (failmsg) => {
                // console.log(failmsg)
              }
            })
          } else if (this.formData.type == 27 && res.data.HipoPayParams){
            const payData = JSON.parse(res.data.HipoPayParams)
            const url = res.data ? res.data.redirect_url:''
            wx.requestPayment({
              timeStamp: payData.timeStamp,
              nonceStr: payData.nonceStr, //
              package: payData.package, //
              signType: payData.signType, //微信签名方式
              paySign: payData.paySign, //微信签名
              success: (res) => {
                // console.log(res)
                openPage(url)
              },
              fail: (failmsg) => {
                // console.log(failmsg)
              }
            })
          } else if (this.formData.type == 24) {
            const payData = JSON.parse(res.data.yatuan_pay_sign)
            const url = res.data ? res.data.redirect_url : ''
            wx.requestPayment({
              timeStamp: payData.timeStamp,
              nonceStr: payData.nonceStr, //
              package: payData.package, //
              signType: payData.signType, // 微信签名方式
              paySign: payData.paySign, // 微信签名
              success: (res) => {
                // console.log(res)
                openPage(url)
              },
              fail: (failmsg) => {
                // console.log(failmsg)
              }
            })
          } else if (this.formData.type == 26 && res.data.is_mini_vsp) {
            this.Jump('/buyTonglianWait',{ order_id: res.data.order_id, pay_type: 3 })
          } else if (this.formData.type == 34) {
            if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
              if (res.data.jsApiParameters) {
                const jsApiParameters = typeof res.data.jsApiParameters === 'object' ? res.data.jsApiParameters : JSON.parse(res.data.jsApiParameters) 
                this.hfAppId = jsApiParameters.wx_app_id
                const that = this
                wx.navigateToMiniProgram({
                  appId: jsApiParameters.wx_app_id,
                  path: jsApiParameters.miniapp_path,
                  success(res) {
                    // 打开成功
                    // console.log(res)
                  },
                  fail(error) {
                    // that.$Error('跳转失败')
                    that.Jump('pointOrder')
                  }
                })
              } else {
                openPage(res.data.redirect_url)
              }

            } else if (small.wxCache('adapayPlugVersion') == 'self') {
              const payData = JSON.parse(res.data.jsApiParameters)
              const url = res.data ? res.data.redirect_url:''
              wx.requestPayment({
                timeStamp: payData.timeStamp,
                nonceStr: payData.nonceStr, //
                package: payData.package, //
                signType: payData.signType, //微信签名方式
                paySign: payData.paySign, //微信签名
                success: (res) => {
                  // console.log(res)
                  openPage(url)
                },
                fail: (failmsg) => {
                  // console.log(failmsg)
                }
              })
            } else {
              const adapayPlugin = small.wxCache('adapayPlugVersion') == 'new' ? requirePlugin("Adapay") : requirePlugin("adapay-plugin")              
              // 汇付分账
              this.isSubmit = false
              // console.log('typeof obj',  typeof res.data.jsApiParameters === 'object')
              const hfPay= res.data.jsApiParameters
              if (hfPay) {
                adapayPlugin.requestPay(hfPay, this.paySuccess, this.payError);
              } else {
                openPage(res.data.redirect_url)
              }
            }
          } else{
            // TODO 跳转
            if (res.data && res.data.redirect_url) {
              if (this.paymentWay != 'peerpay ') {
                this.$Error('支付成功')
              }
              setTimeout(() => {
                openPage(res.data.redirect_url)
              }, 1000)
            }
          }
        } else {
          this.$Error(res.msg)
        }
      })
    },
    Jump(url, data) {
      this.$JumpPath(this, url, data)
    },
    // 选中国际支付宝抛出的值
    globalAlipay(val) {
      this.formData.global_alipay_currency = val
    },
    // 获取运费
    getPostFee() {
      const data = {
        freight_tpl_id: this.resData.freight_tpl_id,
        item_total_num: this.resData.item_total_num,
        province_id: this.formData.province_id,
        area_id: this.formData.area_id,
        city_id: this.formData.city_id,
        item_total_weight: this.resData.item_total_weight,
        volume: this.resData.item_total_volume,
        shipping_type: this.formData.shipping_type,
        item_ids: this.item_id,
        nums: this.num
      }
      if (this.resData.item_total_num && this.resData.freight_tpl_id) {
        if (this.resData.cart == 1) {
          // 积分购物车运费计算
          getPointPostFee(data).then(res => {
            if (res.status == 1) {
              this.postFee = parseFloat(res.data.post_fee).toFixed(2)
            } else {
              this.$Error(res.msg)
            }
          })
        } else {
        // 普通运费
          getPostFee(data).then(res => {
            if (res.status == 1) {
              this.postFee = parseFloat(res.data.post_fee).toFixed(2)
            } else {
              this.$Error(res.msg)
            }
          })
        }
      }
    },
    // 积分兑换商品判断余额是否足够支付
    pointBuyCompare() {
      // 判断余额是否充足支付
      if (this.money_type && this.user_balance > this.postFee) {
        this.isShowOtherPayment = false
      } else {
        this.isShowOtherPayment = true
      }
      // 汇付支付不允许混合支付
      if (this.resData.is_adapay_pay) {
        if (this.user_balance - 0 < this.postFee - 0) {
          this.money_type = ''
          this.hfShowNoPay = true
        } else {
          this.hfShowNoPay = false
        }
        // console.log('this.hfshow1', this.hfShowNoPay)
      }
    },
    // 显示选择预约时间弹窗
    selectSubDate() {
      this.$refs.subscribe.clickStart()
    },
    // 获取配送方式
    getShippingType(data) {
      this.formData.shipping_type = data
    },
    // 获取自提地址
    getSelfAddress(val) {
      this.selfAddressInfo = val
      // // console.log(val, 2222)
    },
    // 获取日期时间
    getDateTime(val) {
      this.$refs.subscribe.columns = val
      // // console.log(val)
    },
    // 获取预约日期和时间
    dateTime(date, time) {
      this.formData.reservation_service_date = date
      this.formData.reservation_service_time = time
      this.subscribeTime = date + ' ' + time
    },
    // 点击选择自提地址
    openSelfAddress() {
      // 调用子组件方法
      if (this.$refs.modeDistribution) {
        this.$refs.modeDistribution.selfAddressVisible = true
        this.$refs.modeDistribution.$refs.selfAddressDialog.dialogVisible = true
      }
    }
  }
})
</script>

<style lang="scss">
@import "src/styles/mixin";
@import "src/styles/order/orderBuy";
</style>
